var lodash = require('lodash');
var httpreq = require('httpreq');
var webconfig = require('../../../../../../webconfig').webconfig;
// ldc 设置一个固定的token 后期进行token获取的重新设计
var headers = {
    "token": "V0VJWElOOiQqJTp3ZWl4aW4xMjM0NTZAIyQ=",
    "storeId": webconfig.storeId
};

function setHeaders(config) {
    if (!config) config = {};
    if (config.headers) {
        config.headers.token = headers.token;
        config.headers.storeId = headers.storeId;
    }
    else {
        config.headers = headers;
    }   
    return config;
}

function get(url, config) {
    config = setHeaders(config);
    return (<any>Promise).promisify(httpreq.get)(url, config).then(function (res) {
        if (res.statusCode >= 400) {
            throw res;
        }
        return JSON.parse(res.body);
    });
}

function put(url, config) {
    config = setHeaders(config);
    return (<any>Promise).promisify(httpreq.put)(url, config).then(function (res) {
        if (res.statusCode >= 400) {
            throw res;
        }
        var isJson = res.headers['content-type'] && res.headers['content-type'].split(';')[0] == 'application/json';
        return isJson ? res.body && JSON.parse(res.body) : res.body;
    });
}

module.exports = {
    get: get,
    put: put
};